package com.gitee.cui.basic.use;

import com.gitee.cui.util.JvmUtil;
import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * 测试线程睡眠
 */
@Slf4j
public class Sleep {

    /**
     * 睡眠时长
     */
    public static final int SLEEP_GAP = 5000;
    /**
     * 睡眠次数
     */
    public static final int MAX_TURN = 50;

    static class SleepThread extends Thread {
        static int threadSeqNumber = 1;

        public SleepThread() {
            super("sleepThread-" + threadSeqNumber);
            threadSeqNumber++;
        }

        public void run() {
            try {
                for (int i = 1; i < MAX_TURN; i++) {
                    log.info(getName() + ", 睡眠轮次：{}", i);
                    // 线程睡眠一会
                    Thread.sleep(SLEEP_GAP);
                }
            } catch (InterruptedException e) {
                log.info(getName() + " 发生异常被中断.");
            }
            log.info(getName() + " 运行结束.");
        }

    }

    public static void main(String args[]) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            Thread thread = new SleepThread();
            thread.start();
        }
        log.info(ThreadUtil.getCurThreadName() + " 运行结束.");
    }


    @Test
    public void sleepForever() {
        // 获取进程id，避免去任务管理器查找
        log.info("进程ID=" + JvmUtil.getProcessID());
        try {
            // main线程，无限制等待
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}